package com.example.testplatform.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 日志工具类，提供统一的日志记录方法
 */
public class LogUtils {

    /**
     * 获取日志记录器
     */
    public static Logger getLogger(Class<?> clazz) {
        return LoggerFactory.getLogger(clazz);
    }

    /**
     * 获取日志记录器
     */
    public static Logger getLogger(String name) {
        return LoggerFactory.getLogger(name);
    }

    /**
     * 记录调试日志，只有当DEBUG级别启用时才执行supplier
     */
    public static void debug(Logger logger, Supplier<String> messageSupplier) {
        if (logger.isDebugEnabled()) {
            logger.debug(messageSupplier.get());
        }
    }

    /**
     * 记录调试日志，只有当DEBUG级别启用时才执行supplier
     */
    public static void debug(Logger logger, Supplier<String> messageSupplier, Throwable t) {
        if (logger.isDebugEnabled()) {
            logger.debug(messageSupplier.get(), t);
        }
    }

    /**
     * 记录信息日志，只有当INFO级别启用时才执行supplier
     */
    public static void info(Logger logger, Supplier<String> messageSupplier) {
        if (logger.isInfoEnabled()) {
            logger.info(messageSupplier.get());
        }
    }

    /**
     * 记录信息日志，只有当INFO级别启用时才执行supplier
     */
    public static void info(Logger logger, Supplier<String> messageSupplier, Throwable t) {
        if (logger.isInfoEnabled()) {
            logger.info(messageSupplier.get(), t);
        }
    }

    /**
     * 记录警告日志
     */
    public static void warn(Logger logger, String message) {
        logger.warn(message);
    }

    /**
     * 记录警告日志
     */
    public static void warn(Logger logger, String message, Throwable t) {
        logger.warn(message, t);
    }

    /**
     * 记录警告日志，带参数占位符
     */
    public static void warn(Logger logger, String message, Object... args) {
        logger.warn(message, args);
    }

    /**
     * 记录警告日志，带参数占位符和异常信息
     */
    public static void warn(Logger logger, String message, Throwable t, Object... args) {
        logger.warn(message, args, t);
    }

    /**
     * 记录警告日志，只有当WARN级别启用时才执行supplier
     */
    public static void warn(Logger logger, Supplier<String> messageSupplier) {
        if (logger.isWarnEnabled()) {
            logger.warn(messageSupplier.get());
        }
    }

    /**
     * 记录错误日志
     */
    public static void error(Logger logger, String message) {
        logger.error(message);
    }

    /**
     * 记录错误日志
     */
    public static void error(Logger logger, String message, Throwable t) {
        logger.error(message, t);
    }

    /**
     * 记录API请求日志
     */
    public static void logApiRequest(Logger logger, String method, String url, Object params) {
        if (logger.isDebugEnabled()) {
            logger.debug("API请求: {} {}", method, url);
            if (params != null) {
                logger.debug("请求参数: {}", params);
            }
        }
    }

    /**
     * 记录API响应日志
     */
    public static void logApiResponse(Logger logger, String method, String url, int statusCode, Object response) {
        if (logger.isDebugEnabled()) {
            logger.debug("API响应: {} {} [{}]", method, url, statusCode);
            if (response != null) {
                logger.debug("响应数据: {}", response);
            }
        }
    }

    /**
     * 记录API错误日志
     */
    public static void logApiError(Logger logger, String method, String url, Exception e) {
        logger.error("API请求异常: {} {}", method, url, e);
    }

    /**
     * 记录业务操作日志
     */
    public static void logBusiness(Logger logger, String operation, String userId, String details) {
        logger.info("业务操作: [操作={}, 用户={}] {}", operation, userId, details);
    }

    /**
     * 记录系统事件日志
     */
    public static void logSystemEvent(Logger logger, String event, String details) {
        logger.info("系统事件: [事件={}] {}", event, details);
    }

    /**
     * 安全日志记录
     */
    public static void logSecurityEvent(Logger logger, String event, String username, String details) {
        logger.info("安全事件: [事件={}, 用户={}] {}", event, username, details);
    }

    /**
     * 性能日志记录
     */
    public static void logPerformance(Logger logger, String operation, long startTime, long endTime) {
        long duration = endTime - startTime;
        logger.info("性能监控: [操作={}] 耗时={}ms", operation, duration);
        if (duration > 1000) { // 超过1秒的操作记录警告
            logger.warn("性能警告: [操作={}] 耗时过长: {}ms", operation, duration);
        }
    }

    /**
     * 敏感信息掩码处理
     */
    public static String maskSensitiveInfo(String info) {
        if (!StringUtils.hasText(info)) {
            return info;
        }
        // 简单的密码掩码处理
        if (info.contains("password") || info.contains("token")) {
            return info.replaceAll("(password|token)\\s*[:=]\\s*\"[^\"]*\"", "$1: ***");
        }
        return info;
    }

    /**
     * 格式化异常信息
     */
    public static String formatException(Exception e) {
        if (e == null) {
            return "无异常信息";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(e.getClass().getName()).append(": ").append(e.getMessage());
        if (e.getStackTrace() != null && e.getStackTrace().length > 0) {
            sb.append("\n\tat ").append(e.getStackTrace()[0]);
            // 只取前5行栈信息
            int stackTraceCount = Math.min(5, e.getStackTrace().length);
            for (int i = 1; i < stackTraceCount; i++) {
                sb.append("\n\tat ").append(e.getStackTrace()[i]);
            }
            if (e.getStackTrace().length > stackTraceCount) {
                sb.append("\n\t... ").append(e.getStackTrace().length - stackTraceCount).append(" more...");
            }
        }
        return sb.toString();
    }

    /**
     * 参数校验并记录日志
     */
    public static boolean validateParams(Logger logger, Object... params) {
        boolean allValid = Arrays.stream(params).allMatch(Objects::nonNull);
        if (!allValid) {
            logger.warn("参数校验失败: 存在空参数");
        }
        return allValid;
    }
}